#include "stdafx.h"

#include <fstream>

#include "Language.h"

bool CLanguage::ReadFile(CString fileName)
{
	bool rtn = true;

	if(m_Lines.find(fileName) != m_Lines.end())
	{
		m_Lines[fileName].clear();
	}

	ifstream inputFile(fileName);

	if(inputFile.is_open())
	{
		CString line = _T("");
		char inpline[MAX_LINE_LENGTH];
		while(inputFile.good())
		{
			line = _T("");
			inputFile.getline(inpline, MAX_LINE_LENGTH);
			line.Format(_T("%s"), inpline);
			m_Lines[fileName].push_back(line);
		}
		inputFile.close();
	}
	else
	{
		rtn = false;
		CString tmp;
		tmp.Format(_T("Error opening file<%s>"),fileName);
		m_Errors.NewError(tmp, -1, fileName, ERROR_FILE);
	}

	return rtn;
}

bool CLanguage::ParseParenFile(CString fileName)
{
	bool rtn = true;

	CString line;
	char top;
	int curLine = 0;
	CString errorText;
	while(!m_BraceStack.empty())
		m_BraceStack.pop();
	for(list<CString>::iterator itr2 = m_Lines[fileName].begin();
		itr2 != m_Lines[fileName].end(); itr2++)
	{
		line.Format(_T("%s"),*itr2);
		curLine++;
		bool insideQuote = false;
		// If no special characters found on this line, skip it
		if(line.Find('{') == -1 && line.Find('(') == -1 && line.Find('}') == -1 &&
			line.Find(')') == -1 && line.Find('"') == -1)
			continue;
		// Scan every character on the line
		for(int i=0; i < line.GetLength(); i++)
		{
			// ignore everything inside of quotes
			if(line.GetAt(i) == '{' && insideQuote == false)
			{
				m_BraceStack.push('{');
			}
			else if(line.GetAt(i) == '}' && insideQuote == false)
			{
				m_BraceStack.push('(');
			}
			else if(line.GetAt(i) == '}' && insideQuote == false)
			{
				top = m_BraceStack.top();
				m_BraceStack.pop();
				if(top != '{')
				{
					errorText.Format(_T("Brace Error: Found <%c> expected <{>"),top);
					m_Errors.NewError(errorText, curLine, fileName, ERROR_BRACE);
					rtn  = false;
				}
			}
			else if(line.GetAt(i) == ')' && insideQuote == false)
			{
				top = m_BraceStack.top();
				m_BraceStack.pop();
				if(top != '(')
				{
					errorText.Format(_T("Paren Error: Found <%c> expected <(>"),top);
					m_Errors.NewError(errorText, curLine, fileName, ERROR_PAREN);
					rtn = false;
				}
			}
			else if(line.GetAt(i) == '"')
			{
				insideQuote = !insideQuote;
			}

			if(rtn == false)
			{
				return rtn;
			}

			if(insideQuote == true)
			{
				errorText.Format(_T("Quote Error: unbalanced quotation marks"), top);
				m_Errors.NewError(errorText, curLine, fileName, ERROR_QUOTE);
				return false;
			}
		}
	}

	return rtn;
}